﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Web.DbHelper;
using KnowledgeCommunity.Service;
using System.IO;

namespace KnowledgeCommunity.Web.Controllers
{
    public class AccountController : Controller
    {
        UserAccountHelper myUserAccountHelper = new UserAccountHelper();
        //
        // GET: /UserAccount/

        [Authorize(Roles = "admin")]
        public ActionResult Index()
        {
            KnowledgeCommunity.Web.Models.Page Model = new Page();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<UserAccount> datesource = GetDataSource();//要分页的数据源
            Model.UserAccountList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.UserAccountList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);
        }

        private List<UserAccount> GetDataSource()
        {
            var UserAccount = myUserAccountHelper.FindAll();
            List<UserAccount> model = new List<UserAccount>();
            foreach (var item in UserAccount)
            {
                model.Add(item);
            }
            return model;
        }

        [Authorize(Roles = "admin")]
        public ActionResult PageIndex(Models.Page Model)
        {

            //分页数据源。自己写逻辑获取。

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<UserAccount> datesource = GetDataSource();//要分页的数据源
            Model.UserAccountList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Search()
        {
            string title = Request.Form["s_title"];
            int _role = Convert.ToInt32(Request.Form["s_role"]);
            DateTime start, end;
            start = Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-12-31");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }
            var apps = myUserAccountHelper.SearchByKeyAndTime(title, _role, start, end);
            return View(apps);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Details(int id)
        {
            var model = myUserAccountHelper.FindById(id);
            return View(model);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id) 
        {
            var model = myUserAccountHelper.FindById(id);
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Edit(UserAccount model)
        {
            model.Role = Convert.ToInt32(Request.Form["urole"]);
            model.State = Convert.ToInt32(Request.Form["ustate"]);
            DoUpdateModel(model);
            return Index();
        }

        [Authorize]
        public ActionResult UserInfo()
        {
            string user=HttpContext.User.Identity.Name;
            var model = myUserAccountHelper.FindByUserName(user);
            return View(model);
        }

        [Authorize]
        [HttpPost]
        public ActionResult UserInfo(UserAccount model)
        {
            
            string fileOldName = null;
            string extension = null;
            string path = "";
            string url = "";

            foreach (string image in Request.Files)
            {
                if (!HasFiles.HasFile(Request.Files[image]))
                    continue;

                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"UpLoad\UserAccounts" + "\\"+ model.UserName;
                path = HasFolders.HasFolder(createPath);

                //获得文件扩展名
                fileOldName = Path.GetFileName(Request.Files[image].FileName);
                extension = Path.GetExtension(fileOldName);//扩展名 ".xxx"

                string miniType = Request.Files[image].ContentType.ToLower();

                Stream fileStream = Request.Files[image].InputStream;

                //文件重命名
                string fileNewName = RandomNumber.RandomNumberToName() + extension;

                Request.Files[image].SaveAs(Path.Combine(path, fileNewName));

                path = path + "\\" + fileNewName;
                url = "~\\UpLoad\\UserAccounts\\" + model.UserName + "\\" + fileNewName;

            }
            if (path != "" && url != "")
            {
                //model.ImgUrl = url;
                //model.DelPath = path;
            }
            try 
            {
                DoUpdateModel(model);
                return UserInfo();
            }
            catch
            {
                //回滚操作！
                //System.IO.File.Delete(path);
                return RedirectToAction("Error", "Notice", new { type = 1 });
            }
        }

        [Authorize(Roles = "admin")]
        public ActionResult Delete(int id)
        {
            var _UserAccount = myUserAccountHelper.FindById(id);
            return View(_UserAccount);
        }

        [Authorize(Roles = "admin")]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            bool n = myUserAccountHelper.Delete(id);
            if (n)
                return Index();
            else
                return RedirectToAction("Error", "Notice", new { type = 2 });
        }

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    UserAccount myAccount=new UserAccount()
                    {
                        UserName=model.UserName,
                        Email=model.Email,
                        AddTime=DateTime.Now,
                        State=1,
                        Role=1,
                        Telephone=model.Telephone,
                        ImgUrl="~\\Content\\images\\user_1.png",
                        Password=model.Password
                    };

                    myUserAccountHelper.Create(myAccount);
                    return RedirectToAction("Index", "Zone");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        CKCDB mydb = new CKCDB();
        private void DoUpdateModel(UserAccount model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var app = mydb.UserAccounts.Find(model.Id);
                    UpdateModel(app);
                    mydb.SaveChanges();
                }
                catch (Exception ex)
                {
                    string message = "Create in table<Commodity>" + ex.ToString();
                    WriteLog.WriteSysLog(message);
                }
            }
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
